﻿using AutoMapper;
using MediatR;
using SC.GirdManage.Common;
using SC.GirdManage.Repository;
using SC.GridManage.API.Write.Application.Command.LogicGrid;
using SC.GridManage.Domain.Models;

namespace SC.GridManage.API.Write.Application.Handler.LogicGrid
{
    public class UpdLogicGridHandler : IRequestHandler<UpdLogicGridCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<LogicGridModel> logicGridRepo;
        private readonly IMapper mapper;

        public UpdLogicGridHandler(IBaseRepository<LogicGridModel> logicGridRepo, IMapper mapper)
        {
            this.logicGridRepo = logicGridRepo;
            this.mapper = mapper;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiResult<int>> Handle(UpdLogicGridCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();

             var logicCount = logicGridRepo.QueryAsync().Result.Where(x => x.Id != request.Id && x.GridNo == request.GridNo).Count();
            if (logicCount>0)
            {
                result.Code = GirdManage.Common.Enums.EnumResultCode.Fail;
                result.Msg = "已经存在相同名称的逻辑网格编号";
                return Task.FromResult(result);
            }

            var model = mapper.Map<LogicGridModel>(request);
           int r = logicGridRepo.UpdateAsync(model).Result;

            //判断添加受影响的行数
            if (r > 0)
            {
                result.Code = GirdManage.Common.Enums.EnumResultCode.Success;
                result.Msg = "更新逻辑网格成功";
                result.Data = r;
            }
            else
            {
                result.Code = GirdManage.Common.Enums.EnumResultCode.Fail;
                result.Msg = "更新逻辑网格失败";
                result.Data = r;
            }


            return Task.FromResult(result);
        }
    }
}
